import React, { Component } from 'react';
import { Upload, message, Menu, Dropdown, Button } from 'antd';
import { LoadingOutlined, PlusOutlined, PictureOutlined, CloseOutlined } from '@ant-design/icons';
import styles from './index.less';

// function getBase64(img, callback) {
//   const reader = new FileReader();
//   reader.addEventListener('load', () => callback(reader.result));
//   reader.readAsDataURL(img);
// }

export default class ImageBox extends Component {
  constructor(props) {
    super(props);

    this.state = {
      loading: false,
      imageUrl: '',
    };
  }
  triggerChange(changedValue) {
    if (this.props.onChange) {
      const obj = {
        ...this.state,
        ...changedValue,
      };
      this.props.onChange(obj.imageUrl);
    }
  }

  handleChange(info) {
    if (info.file.status === 'uploading') {
      this.setState({ loading: true });
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      // console.log(info.file.response);
      // const host = 'http://localhost:5793';
      if (info.file.response.success) {

        const imageUrl = info.file.response.result[0];
        this.setState({
          imageUrl,
          loading: false,
        });
        this.triggerChange({ imageUrl });
      }
      // getBase64(info.file.originFileObj, imageUrl => {
      //   this.setState({
      //     imageUrl,
      //     loading: false,
      //   })
      //   this.triggerChange({ imageUrl })
      // });
    }
  }

  render() {

    const imagesUrl = this.props.arr ? this.props.arr : [];
    const imageUrl = this.props.value ? this.props.value : this.state.imageUrl;
    const maxSize = this.props.maxSize != undefined ? this.props.maxSize : 2;
    return (
      <div className={styles.block}>
        <Upload
          accept="image/png,image/jpeg"
          name="avatar"
          listType="picture-card"
          className={styles.Upload}
          showUploadList={false}
          headers={{ auth: localStorage.getItem("authInfo") }}
          action={this.props.action}
          // action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
          beforeUpload={(file) => {
            const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
            if (!isJpgOrPng) {
              message.error('仅仅支持 JPG/PNG 文件!');
            }

            const isLt2M = file.size / 1024 / 1024 < maxSize;
            if (!isLt2M) {
              message.error(`图片必须小于 ${maxSize}MB!`);
            }
            return isJpgOrPng && isLt2M;
          }}
          onChange={(info) => {
            this.handleChange(info);
          }}
        >
          {imageUrl ? (
            <img src={imageUrl} alt="avatar" style={{ width: '100%' }} />
          ) : (
              <div>
                {this.state.loading ? <LoadingOutlined /> : <PlusOutlined />}
                <div>本地上传</div>
              </div>
            )}
        </Upload>
        {imagesUrl.length !== 0 ? (
          <Dropdown
            className={styles.Dropdown}
            overlay={
              <Menu
                onClick={({ key }) => {
                  this.setState({
                    imageUrl: imagesUrl[Number(key)],
                  });
                  this.triggerChange({ imageUrl: imagesUrl[Number(key)] });
                }}
              >
                {imagesUrl.map((item, index) => (
                  <Menu.Item key={index}>
                    <span className={styles.MenuLink}>
                      <img src={item} alt="" />
                    </span>
                  </Menu.Item>
                ))}
              </Menu>
            }
          >
            <Button>
              <PictureOutlined />
              从正文中选择封面图片
            </Button>
          </Dropdown>
        ) : null}
        {imageUrl != "" ? <CloseOutlined
          onClick={() => {
            this.setState({
              imageUrl: "",
            });
            this.triggerChange({ imageUrl: "" });
          }}
          className={styles.closeBox} /> : null}


        {/* <pre className="language-bash">{JSON.stringify(this.props.arr, null, 2)}</pre> */}
      </div>
    );
  }
}
